package com.cxyd.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxyd.common.page.PageData;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ProcResult;
import com.cxyd.modules.log.service.SysLogWorkService;
import com.cxyd.modules.security.user.SecurityUser;
import com.cxyd.modules.sys.dao.SysParamsDao;
import com.cxyd.modules.sys.dto.SysUserDTO;
import com.cxyd.modules.sys.service.SysUserService;
import com.cxyd.modules.wms.dao.*;
import com.cxyd.modules.wms.dto.ErpReelDTO;
import com.cxyd.modules.wms.dto.TaskDTO;
import com.cxyd.modules.wms.entity.*;
import com.cxyd.modules.wms.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务记录
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@Service
public class TaskServiceImpl extends CrudServiceImpl<TaskDao, TaskEntity, TaskDTO> implements TaskService {

    private final SysUserService userService;
    private final LocateDao locateDao;
    private final ContainerDao containerDao;
    private final ContainerService containerService;
    private final ContainerDetailDao containerDetailDao;
    private final ContainerDetailService containerDetailService;
    private final PostWcsService postWcsService;
    private final ErpReelDao erpReelDao;
    private final ErpReelService erpReelService;
    private final ErpLogDao erplogDao;
    private final StockDao stockDao;
    private final PurchaseDetailDao purchaseDetailDao;
    private final OrderDetailDao orderDetailDao;
    private final OrderReelDao orderReelDao;
    private final PostWcsDao postWcsDao;
    private final PostSapDao postSapDao;
    private final SpuDao spuDao;
    private final SysParamsDao sysParamsDao;
    private final SysLogWorkService sysSysLogWorkService;

    public TaskServiceImpl(SysUserService userService, LocateDao locateDao, ContainerDao containerDao, ContainerDetailDao containerDetailDao, ContainerDetailService containerDetailService, ContainerService containerService, PostWcsService postWcsService, ErpReelDao erpReelDao, ErpReelService erpReelService, ErpLogDao erplogDao, StockDao stockDao, PurchaseDetailDao purchaseDetailDao, OrderDetailDao orderDetailDao, OrderReelDao orderReelDao, PostWcsDao postWcsDao, PostSapDao postSapDao, SpuDao spuDao, SysParamsDao sysParamsDao, SysLogWorkService sysSysLogWorkService) {
        this.userService = userService;
        this.locateDao = locateDao;
        this.containerDao = containerDao;
        this.containerDetailDao = containerDetailDao;
        this.containerDetailService = containerDetailService;
        this.containerService = containerService;
        this.postWcsService = postWcsService;
        this.erpReelDao = erpReelDao;
        this.erpReelService = erpReelService;
        this.erplogDao = erplogDao;
        this.stockDao = stockDao;
        this.purchaseDetailDao = purchaseDetailDao;
        this.orderDetailDao = orderDetailDao;
        this.orderReelDao = orderReelDao;
        this.postWcsDao = postWcsDao;
        this.postSapDao = postSapDao;
        this.spuDao = spuDao;
        this.sysParamsDao = sysParamsDao;
        this.sysSysLogWorkService = sysSysLogWorkService;
    }

    @Override
    public PageData<TaskDTO> page(Map<String, Object> params) {
        //1.获取任务信息
        final IPage<TaskEntity> page = baseDao.selectPage(
                getPage(params, "task_id", false),
                getWrapper(params)
        );
        //2.获取用户列表
        final List<SysUserDTO> userList = userService.getList();
        //3.将creator与updater的username通过id进行绑定
        page.getRecords().forEach(entity -> {
            if (entity.getCreator() != null) {
                entity.setCreatorName(userService.getUsernameById(entity.getCreator(), userList));
            }
            if (entity.getUpdater() != null) {
                entity.setUpdaterName(userService.getUsernameById(entity.getUpdater(), userList));
            }
        });
        return getPageData(page, TaskDTO.class);
    }

    @Override
    public QueryWrapper<TaskEntity> getWrapper(Map<String, Object> params) {
        String taskId = (String) params.get("taskId");
        String taskType = (String) params.get("taskType");
        String taskSubType = (String) params.get("taskSubType");
        String contNo = (String) params.get("contNo");
        String spuNo = (String) params.get("spuNo");
        String spuName = (String) params.get("spuName");
        String fromPosition = (String) params.get("fromPosition");

        String mtNo = (String) params.get("mtNo");
        String detailId = (String) params.get("detailId");
        //String taskSt = (String) params.get("taskSt");

        Integer taskSt = ObjectUtils.isNotEmpty(params.get("taskSt")) ? Integer.parseInt((String) params.get("taskSt")) : null;


        QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(taskId), "task_id", taskId);
        wrapper.eq(StringUtils.isNotBlank(taskType), "task_type", taskType);
        wrapper.eq(StringUtils.isNotBlank(taskSubType), "task_sub_type", taskSubType);
        wrapper.eq(StringUtils.isNotBlank(mtNo), "mt_no", mtNo);
        wrapper.eq(StringUtils.isNotBlank(fromPosition), "from_position", fromPosition);
        wrapper.eq(StringUtils.isNotBlank(detailId), "detail_id", detailId);
//        if (StringUtils.isBlank(taskSt)) {
//            wrapper.lt("task_st", 9);
//        } else {
//            wrapper.eq("task_st", taskSt);
//        }

        wrapper.eq(ObjectUtils.isNotEmpty(taskSt), "task_st", taskSt);
        wrapper.like(StringUtils.isNotBlank(contNo), "cont_no", contNo);
        wrapper.like(StringUtils.isNotBlank(spuNo), "spu_no", spuNo);
        wrapper.like(StringUtils.isNotBlank(spuName), "spu_name", spuName);

        return wrapper;
    }

    @Override
    public PageData<TaskDTO> rfPage(Map<String, Object> params) {
        final String contNo = (String) params.get("contNo");
        if (StringUtils.isBlank(contNo)) {
            return null;
        }
        final String taskType = (String) params.get("taskType");
        final String taskSubType = (String) params.get("taskSubType");
        final QueryWrapper<TaskEntity> rfWrapper = new QueryWrapper<>();
        rfWrapper.eq("cont_no", contNo);
        rfWrapper.eq(StringUtils.isNotBlank(taskType), "task_type", taskType);
        rfWrapper.eq(StringUtils.isNotBlank(taskSubType), "task_sub_type", taskSubType);
        rfWrapper.lt("task_st", 2);
        final IPage<TaskEntity> page = baseDao.selectPage(getPage(params, "task_id", true),
                rfWrapper
        );
        return getPageData(page, TaskDTO.class);
    }

    @Override
    public PageData<TaskDTO> contBackList(Map<String, Object> params) {
        //1.获取放行任务信息
        Map<String, Object> queryPara = new HashMap<>();
        String stn = (String) params.get("stn");
        String dvcNo = stn.equals("A区") ? "A" : "B";
        String fromLocate = "";

        try {
            fromLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                    .eq("locate_type", "STX")
                    .eq("active", 1)
                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位


            queryPara.put("taskSt", "1");
            queryPara.put("fromPosition", fromLocate);
            final IPage<TaskEntity> page = baseDao.selectPage(
                    getPage(queryPara, "task_id", true),
                    getWrapper(queryPara)
            );
            return getPageData(page, TaskDTO.class);

        } catch (Exception ex) {
            return null;

        }

    }

    //    @Override
//    public ProcResult taskAffirm(Map<String, Object> params) {
//        //对主要参数进行校验
//        final String taskId = (String) params.get("taskId");
//        if (StringUtils.isBlank(taskId)) {
//            return new ProcResult().result("123", "任务号不能为空!");
//        }
//        baseDao.procTaskAffirm(params);
//        final String code = (String) params.get("code");
//        final String msg = (String) params.get("msg");
//        return new ProcResult().result(code, msg);
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProcResult taskAffirm(Map<String, Object> params) {
        ProcResult result = new ProcResult();

        try {
            String contNo = (String) params.get("contNo");//0-空托盘登记 1-入库登记 2-盘点回库
            String reelId = (String) params.get("reelId");

            Long userId = SecurityUser.getUser().getId();
            String userNo = SecurityUser.getUser().getUsername();
            String userName = SecurityUser.getUser().getRealName();
            Date now = new Date();

            //查看有沒有這筆庫存
            if (!stockDao.exists(new QueryWrapper<StockEntity>()
                    .eq("cont_no", contNo)
                    .eq("reel_id", reelId))) {
                throw new Exception("箱號【" + contNo + "】裏沒有reelid【" + reelId + "】庫存");
            }
            //查看有沒有出庫任務
            if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                    .eq("cont_no", contNo)
                    .eq("reel_id", reelId)
                    .eq("detail_st", 0))) {
                throw new Exception("箱號【" + contNo + "】分配reelid【" + reelId + "】庫存出庫任務");
            }
            //獲取單據
            OrderReelEntity orderReel = null;
            try {
                orderReel = orderReelDao.selectOne(new QueryWrapper<OrderReelEntity>()
                        .eq("cont_no", contNo)
                        .eq("reel_id", reelId)
                        .eq("detail_st", 0)
                        .orderByAsc("zllbh")
                        .orderByAsc("detail_id")
                        .last("limit 1")); //ADD BY LP 2025/2/15 找不到重复的原因

            } catch (Exception ex) {
                throw new Exception("箱號【" + contNo + "】,reelid【" + reelId + "】存在多條出庫任務");

            }

            //更新reelid出庫單狀態
            orderReel.setDetailSt(1);
            orderReel.setUpdater(userId);
            orderReel.setUpdateDate(now);
            orderReelDao.updateSt(orderReel);
            //更新工單出庫單
            if (orderReel.getDetailId() != null) {

                OrderDetailEntity orderDetail = orderDetailDao.selectOne(new QueryWrapper<OrderDetailEntity>()
                        .eq("detail_id", orderReel.getDetailId()));
                orderDetail.setActlQty(orderDetail.getActlQty().add(orderReel.getPlanQty()));
                if (!(orderDetail.getPlanQty().compareTo(orderDetail.getActlQty()) > 0))
                    orderDetail.setDetailSt(2);
                orderDetail.setUpdater(userId);
                orderDetail.setUpdateDate(now);
                orderDetailDao.updateById(orderDetail);//更新工單明細

            }
            //都有就可以刪庫存，更新出庫單狀態
            stockDao.delete(new QueryWrapper<StockEntity>()
                    .eq("cont_no", contNo)
                    .eq("reel_id", reelId));

//            ErpLogEntity logInsert = new ErpLogEntity();
//            logInsert.setRid(reelId);
//            logInsert.setPn(orderReel.getSpuNo());
//            logInsert.setQty(0-orderReel.getPlanQty().longValue());
//            logInsert.setEventid("LGRSTACG");
//            logInsert.setStation(userNo);
//            logInsert.setCompany("PEGATRON");
//            logInsert.setTimestamp(now);
//            logInsert.setRemarks("OUT,"+orderReel.getContLocateNo()+","+userName);
//            logInsert.setUid(userNo);
//            erplogDao.insertLog(logInsert);
            PostSapEntity postSapEntity = new PostSapEntity();
            postSapEntity.setLgnum(reelId);
            postSapEntity.setUname(orderReel.getSpuNo());
            postSapEntity.setSrmdn(orderReel.getContLocateNo());
            postSapEntity.setMenge(orderReel.getPlanQty());
            postSapEntity.setCreator(userId);
            postSapEntity.setComments("OUT," + orderReel.getContLocateNo() + "," + userName);
            postSapEntity.setMsgType("OT");
            postSapEntity.setCreateDate(now);
            postSapDao.insert(postSapEntity);

            result.setCode("0");
            result.setMsg("箱號【" + contNo + "】,reelid【" + reelId + "】揀貨成功");

        } catch (Exception ex) {
            result.setCode("-1");
            result.setMsg(ex.toString());
        }
        return result;
    }

    @Override
    public ProcResult taskCancel(Map<String, Object> params) {
        //业务逻辑...
        baseDao.proTaskCancel(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult emptyRegister(Map<String, Object> params) {
        baseDao.proEmptyRegister(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult emptyCall(Map<String, Object> params) {
        baseDao.proEmptyCall(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult checkAffirm(Map<String, Object> params) {
        String taskId = (String) params.get("taskId");
        String actlQty = (String) params.get("actlQty");
        String spuSize = (String) params.get("spuSize");
        String spuWeight = (String) params.get("spuWeight");
        if (StringUtils.isBlank(taskId)) {
            return new ProcResult().result("123", "盘点确认ID不能为空");
        }
        if (StringUtils.isBlank(actlQty)) {
            return new ProcResult().result("123", "件数不能为空");
        }
        if (StringUtils.isBlank(spuSize)) {
            return new ProcResult().result("123", "尺寸不能为空");
        }
        if (StringUtils.isBlank(spuWeight)) {
            return new ProcResult().result("123", "磅重不能为空");
        }
        baseDao.procCheckAffirm(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProcResult requestContOut(Map<String, Object> params) {
        ProcResult result = new ProcResult();
        String userName = SecurityUser.getUser().getRealName();

        try {
            String requestType = (String) params.get("requestType");
            //获取操作站台
            String stn = (String) params.get("stn");
            String dvcNo = stn.equals("A区") ? "A" : "B";
            Long userId = SecurityUser.getUser().getId();
            Date now = new Date();
            String toLocate = "";
            try {
                toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                        .eq("locate_type", "STS")
                        .eq("active", 1)
                        .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;//出库目标货位

            } catch (Exception ex) {
                throw new Exception("找不到" + stn + "上料口貨位");
            }

            if (requestType.equals("0")) {
                //请求料箱出库
                String contType = (String) params.get("contType");//料箱类型

                String contVolume = (String) params.get("contVolume");//料箱體積

                String contTypeName = "";

                if (contType.equals("1")) {
                    contTypeName = "其他";
                } else if (contType.equals("2")) {
                    contTypeName = "10格";

                } else if (contType.equals("3")) {
                    contTypeName = "16格";

                }
                int num = (Integer) params.get("num");//数量
                int resNum = 0;
                for (int i = 0; i < num; i++) {

                    LocateEntity locateEntity = locateDao.getEmptyCont(dvcNo, contType, contVolume);

                    if (locateEntity == null) {
                        //break;
                        //throw new Exception("庫裏無可用空料箱");

                        //update 20241122
                        locateEntity = locateDao.getContLessuse(dvcNo, contType, contVolume);
                        if (locateEntity == null) {
                            break;
                        }
                    }
                    //生成出库任务

                    TaskEntity taskEntity = new TaskEntity();

                    taskEntity.setTaskType("02");
                    taskEntity.setTaskSubType("021");
                    taskEntity.setContNo(locateEntity.getContNo());
                    taskEntity.setComments("空箱出庫");
                    taskEntity.setTaskSt(1);
                    taskEntity.setFromPosition(locateEntity.getLocateNo());
                    taskEntity.setCurrentPosition(locateEntity.getLocateNo());
                    taskEntity.setToPosition(toLocate);
                    taskEntity.setCreateDate(now);
                    taskEntity.setUpdateDate(now);
                    taskEntity.setCreator(userId);
                    taskEntity.setUpdater(userId);
                    insert(taskEntity);

                    //wms_post_wcs下发设备任务

                    PostWcsEntity postWcsEntity = new PostWcsEntity();
                    postWcsEntity.setContNo(locateEntity.getContNo());
                    postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                    postWcsEntity.setContType(contType);
                    postWcsEntity.setFrmPos(locateEntity.getLocateNo());
                    postWcsEntity.setCurPos(locateEntity.getLocateNo());
                    postWcsEntity.setToPos(toLocate);
                    postWcsEntity.setTrkType("OT");
                    postWcsEntity.setTrkPrty("1");
                    postWcsEntity.setCreateDate(now);
                    postWcsEntity.setUpdateDate(now);
                    postWcsEntity.setCreator(userId);
                    postWcsEntity.setUpdater(userId);
                    postWcsService.insert(postWcsEntity);

                    resNum++;
                }

                //查询在途数量
                //int taskNum = baseDao.selectEmptyCount(contType,dvcNo);

                if (resNum == 0) {
                    //返回成功
                    result.setCode("-1");
//                    result.setMsg("【"+stn+"】庫裏無可用【"+contTypeName+
//                            "】類型空料箱，途中有【"+taskNum+"】個空箱在出庫");
                    result.setMsg("【" + stn + "】庫裏無可用【" + contTypeName +
                            "】類型【" + contVolume + "】體積空料箱");
                } else {
                    //返回成功
                    result.setCode("0");
//                    result.setMsg("【"+stn+"】庫,【"+contTypeName+
//                            "】類型空料箱已成功請求【"+resNum+"】個，途中共有【"+taskNum+"】個空箱在出庫");
                    result.setMsg("【" + stn + "】庫,【" + contTypeName +
                            "】類型【" + contVolume + "】體積空料箱已成功請求【" + resNum + "】個");

                }

            } else if (requestType.equals("1")) {
                //零星出库
                List<String> strArray = (List<String>) params.get("stockIds");

                List<Long> stockIds = strArray.stream()
                        .map(Long::parseLong)
                        .collect(Collectors.toList());

                //插入order_reel
                //更新库存状态
                //生成任务和WCS任务
                for (Long stockId : stockIds) {
                    StockEntity inve = stockDao.selectById(stockId);
                    if (inve.getLockSt() == 1) {
                        throw new Exception("reelid[" + inve.getReelId() + "]庫存凍結狀態不允許出庫");
                    }
                    if (inve.getStockSt() == 1) {
                        throw new Exception("reelid[" + inve.getReelId() + "]庫存已分配不允許重複出庫");
                    }
//                   库存的当前位置要在货位上才行-update by gry 2025年3月11日
                    if(inve.getCurPosition().contains("90000")){
                        throw new Exception("reelid[" + inve.getReelId() + "]庫存尚未回到料架,不允許出庫");
                    }
                    //生成出库明细order_reel
                    if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                            .eq("reel_id", inve.getReelId())
                            .eq("detail_st", 0))) {
                        //此reelid不存在出库任务
                        OrderReelEntity insertOrderReel = new OrderReelEntity();
                        insertOrderReel.setContNo(inve.getContNo());
                        insertOrderReel.setLocate(inve.getCurPosition());
                        insertOrderReel.setSupplier(inve.getPositionType());
                        insertOrderReel.setDatecode(inve.getUnitName());
                        insertOrderReel.setContLocateNo(inve.getContLocateNo());
//                        默认为线边库(原库别#线边库)
                        insertOrderReel.setStockType(inve.getStockType() + "#1");
                        insertOrderReel.setComments("零星出庫");

                        insertOrderReel.setReelId(inve.getReelId());
                        insertOrderReel.setPlanQty(inve.getStockQty());
                        insertOrderReel.setSpuNo(inve.getSpuNo());
                        insertOrderReel.setLotNo(inve.getUnitCode());
                        insertOrderReel.setCreateDate(now);
                        insertOrderReel.setUpdateDate(now);
                        insertOrderReel.setCreator(userId);
                        insertOrderReel.setUpdater(userId);
                        orderReelDao.insert(insertOrderReel);
                        //更新库存状态
                        StockEntity stockUpdate = new StockEntity();
                        stockUpdate.setStockId(inve.getStockId());
                        stockUpdate.setStockType("1");
                        stockUpdate.setStockSt(1);
                        stockDao.updateById(stockUpdate);
                    } else {
                        throw new Exception("reelid[" + inve.getReelId() + "]庫存已分配不允許重複出庫");
                    }

                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                            .eq("locate_no", inve.getCurPosition()));

                    String locateType = locate.getLocateType();
                    if (locateType.equals("HW")) {
                        dvcNo = locate.getDvcNo();
                        try {
                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                    .eq("locate_type", "STS")
                                    .eq("active", 1)
                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                        } catch (Exception ex) {
                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                        }

                        //生成出库任务（有就不生成）（WMS+WCS）
                        if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                .eq("cont_no", inve.getContNo())
                                .eq("task_type", "2")
                                .lt("task_st", 2))) {
                            //不存在就下任务
                            //生成出库任务
                            TaskEntity taskEntity = new TaskEntity();

                            taskEntity.setTaskType("02");
                            taskEntity.setTaskSubType("021");
                            taskEntity.setContNo(inve.getContNo());
                            taskEntity.setComments("料箱零星出庫");
                            taskEntity.setTaskSt(1);
                            taskEntity.setFromPosition(inve.getCurPosition());
                            taskEntity.setCurrentPosition(inve.getCurPosition());
                            taskEntity.setToPosition(toLocate);
                            taskEntity.setCreateDate(now);
                            taskEntity.setUpdateDate(now);
                            taskEntity.setCreator(userId);
                            taskEntity.setUpdater(userId);

                            insert(taskEntity);

                        }

                        //查看是否存在WCS任务，存在就调高优先级，不存在就新增一条任务
                        if (postWcsDao.exists(new QueryWrapper<PostWcsEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("trk_type", "OT")
                                //.eq("trk_prty","3")
                        )) {
                            //如果优先级不是3，需要调高优先级
                            try {
                                PostWcsEntity postWcsUpdate = postWcsDao.selectOne(new QueryWrapper<PostWcsEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("trk_type", "OT")
                                        .eq("trk_st", 1));

                                postWcsUpdate.setTrkPrty("3");
                                postWcsUpdate.setTrkSt(0);
                                postWcsDao.updateById(postWcsUpdate);
                            } catch (Exception ex) {
                                //报错就算了
                            }


                        } else {

                            //wms_post_wcs下发设备任务
                            String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                            PostWcsEntity postWcsEntity = new PostWcsEntity();
                            postWcsEntity.setContNo(inve.getContNo());
                            postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                            postWcsEntity.setContType(contType);
                            postWcsEntity.setFrmPos(inve.getCurPosition());
                            postWcsEntity.setCurPos(inve.getCurPosition());
                            postWcsEntity.setToPos(toLocate);
                            postWcsEntity.setTrkType("OT");
                            postWcsEntity.setTrkPrty("3");
                            postWcsEntity.setCreateDate(now);
                            postWcsEntity.setUpdateDate(now);
                            postWcsEntity.setCreator(userId);
                            postWcsEntity.setUpdater(userId);
                            postWcsService.insert(postWcsEntity);


                        }
                    }

                }

                result.setCode("0");
                result.setMsg("零星出庫成功");

            } else if (requestType.equals("2")) {
                //盤點出庫
                List<String> strArray = (List<String>) params.get("stockIds");

                List<Long> stockIds = strArray.stream()
                        .map(Long::parseLong)
                        .collect(Collectors.toList());
                for (Long stockId : stockIds) {
                    StockEntity inve = stockDao.selectById(stockId);
//                    未在库内的不允许盘点-update by gry 2025年3月11日
                    if(inve.getCurPosition().contains("90000")){
                        throw new Exception("reelid[" + inve.getReelId() + "]庫存尚未回到料架,不允許盤點出庫");
                    }
                    //生成出库任务（有就不生成）（WMS+WCS）

                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                            .eq("locate_no", inve.getCurPosition()));

                    String locateType = locate.getLocateType();
                    if (locateType.equals("HW")) {
                        dvcNo = locate.getDvcNo();
                        try {
                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                    .eq("locate_type", "STS")
                                    .eq("active", 1)
                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                        } catch (Exception ex) {
                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                        }
                        if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                .eq("cont_no", inve.getContNo())
                                .eq("task_type", "2")
                                .lt("task_st", 2))) {
                            //不存在就下任务
                            //生成出库任务


                            TaskEntity taskEntity = new TaskEntity();

                            taskEntity.setTaskType("02");
                            taskEntity.setTaskSubType("021");
                            taskEntity.setContNo(inve.getContNo());
                            taskEntity.setComments("料箱出庫");
                            taskEntity.setTaskSt(1);
                            taskEntity.setFromPosition(inve.getCurPosition());
                            taskEntity.setCurrentPosition(inve.getCurPosition());
                            taskEntity.setToPosition(toLocate);
                            taskEntity.setCreateDate(now);
                            taskEntity.setUpdateDate(now);
                            taskEntity.setCreator(userId);
                            taskEntity.setUpdater(userId);

                            insert(taskEntity);
                        }

                        //查看是否存在WCS任务，存在就调高优先级，不存在就新增一条任务
                        if (postWcsDao.exists(new QueryWrapper<PostWcsEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("trk_type", "OT")
                                //.eq("trk_prty","3")
                        )) {
                            //如果优先级不是3，需要调高优先级
                            try {
                                PostWcsEntity postWcsUpdate = postWcsDao.selectOne(new QueryWrapper<PostWcsEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("trk_type", "OT")
                                        .eq("trk_st", 1));

                                postWcsUpdate.setTrkPrty("3");
                                postWcsUpdate.setTrkSt(0);
                                postWcsDao.updateById(postWcsUpdate);
                            } catch (Exception ex) {
                                //报错就算了
                            }


                        } else {

                            //wms_post_wcs下发设备任务
                            String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                            PostWcsEntity postWcsEntity = new PostWcsEntity();
                            postWcsEntity.setContNo(inve.getContNo());
                            postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                            postWcsEntity.setContType(contType);
                            postWcsEntity.setFrmPos(inve.getCurPosition());
                            postWcsEntity.setCurPos(inve.getCurPosition());
                            postWcsEntity.setToPos(toLocate);
                            postWcsEntity.setTrkType("OT");
                            postWcsEntity.setTrkPrty("3");
                            postWcsEntity.setCreateDate(now);
                            postWcsEntity.setUpdateDate(now);
                            postWcsEntity.setCreator(userId);
                            postWcsEntity.setUpdater(userId);
                            postWcsService.insert(postWcsEntity);

                        }
                    }

                }

                result.setCode("0");
                result.setMsg("料箱出庫成功");

            } else if (requestType.equals("3")) {
                //工單出庫
                //更新 2025-1-2，波次出库，批量

                Long detailId = Long.parseLong((String) params.get("detailId"));

                String orderId = orderDetailDao.selectById(detailId).getZllbh();

                //配货
                List<OrderDetailEntity> orderDetails = orderDetailDao.selectList(new QueryWrapper<OrderDetailEntity>()
                        .eq("zllbh", orderId)
                        .apply("plan_qty > bind_qty"));

                if (orderDetails.stream().count() > 0) {
                    for (OrderDetailEntity obj : orderDetails) {
                        // 对obj进行配货
                        String spuNo = obj.getSpuNo();
                        //BigDecimal needQty= obj.getPlanQty().subtract(obj.getBindQty());
                        //将queryWrapper单独取出做条件判断
                        QueryWrapper<StockEntity> qwCStock = new QueryWrapper<>();
                        qwCStock.eq("spu_no", spuNo);
                        qwCStock.eq("stock_st", 0);
                        qwCStock.eq("lock_st", 0);
                        qwCStock.eq("position_type", obj.getLocate());
                        //只匹配线边库(小库)的库存,大库库存需要先通过转库-2025年2月2日
                        qwCStock.eq("stock_type", "1");
                        qwCStock.orderByAsc("stock_qty");
                        qwCStock.orderByAsc("unit_name");

                        List<StockEntity> stocks = stockDao.selectList(qwCStock);

                        //BigDecimal bindQty = obj.getBindQty();
                        BigDecimal bindQty = BigDecimal.ZERO;
                        for (StockEntity inve : stocks) {
                            //生成出库明细order_reel
                            if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                                    .eq("reel_id", inve.getReelId())
                                    .eq("detail_st", 0))) {
                                //此reelid不存在出库任务
                                OrderReelEntity insertOrderReel = new OrderReelEntity();
                                insertOrderReel.setContNo(inve.getContNo());
                                insertOrderReel.setLocate(inve.getCurPosition());
                                insertOrderReel.setContLocateNo(inve.getContLocateNo());
                                insertOrderReel.setSupplier(inve.getPositionType());
                                insertOrderReel.setDatecode(inve.getUnitName());
//                                insertOrderReel.setStockType(inve.getStockType() + "#1");
                                insertOrderReel.setComments("工單出庫");

                                insertOrderReel.setReelId(inve.getReelId());
                                insertOrderReel.setPlanQty(inve.getStockQty());
                                insertOrderReel.setZllbh(orderId);
                                insertOrderReel.setSpuNo(spuNo);
                                insertOrderReel.setLotNo(inve.getUnitCode());
                                insertOrderReel.setDetailId(obj.getDetailId());
                                insertOrderReel.setCreateDate(now);
                                insertOrderReel.setUpdateDate(now);
                                insertOrderReel.setCreator(userId);
                                insertOrderReel.setUpdater(userId);
                                orderReelDao.insert(insertOrderReel);
                                //更新库存状态
                                StockEntity stockUpdate = new StockEntity();
                                stockUpdate.setStockId(inve.getStockId());
                                stockUpdate.setStockSt(1);
                                stockDao.updateById(stockUpdate);

                                //更新出库单配货数量
                                bindQty = bindQty.add(inve.getStockQty());
                                OrderDetailEntity orderDetailUpdate = new OrderDetailEntity();
                                orderDetailUpdate.setDetailId(obj.getDetailId());
                                orderDetailUpdate.setBindQty(bindQty);
                                orderDetailUpdate.setDetailSt(1);
                                orderDetailDao.updateById(orderDetailUpdate);
                                //生成出库任务（有就不生成）（WMS+WCS）
                                if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("task_type", "2")
                                        .lt("task_st", 2))) {
                                    //不存在就下任务
                                    //生成出库任务
                                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                            .eq("locate_no", inve.getCurPosition()));

                                    String locateType = locate.getLocateType();
                                    if (locateType.equals("HW")) {
                                        dvcNo = locate.getDvcNo();

                                        try {
                                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                                    .eq("locate_type", "STS")
                                                    .eq("active", 1)
                                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                                        } catch (Exception ex) {
                                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                                        }
                                        TaskEntity taskEntity = new TaskEntity();

                                        taskEntity.setTaskType("02");
                                        taskEntity.setTaskSubType("021");
                                        taskEntity.setContNo(inve.getContNo());
                                        taskEntity.setComments("料箱工单出库");
                                        taskEntity.setTaskSt(1);
                                        taskEntity.setFromPosition(inve.getCurPosition());
                                        taskEntity.setCurrentPosition(inve.getCurPosition());
                                        taskEntity.setToPosition(toLocate);
                                        taskEntity.setCreateDate(now);
                                        taskEntity.setUpdateDate(now);
                                        taskEntity.setCreator(userId);
                                        taskEntity.setUpdater(userId);

                                        insert(taskEntity);
                                        //wms_post_wcs下发设备任务
                                        String prty = "1";
                                        if (obj.getIsUg() == 1)
                                            prty = "3";
                                        String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                                        PostWcsEntity postWcsEntity = new PostWcsEntity();
                                        postWcsEntity.setContNo(inve.getContNo());
                                        postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                                        postWcsEntity.setContType(contType);
                                        postWcsEntity.setFrmPos(inve.getCurPosition());
                                        postWcsEntity.setCurPos(inve.getCurPosition());
                                        postWcsEntity.setToPos(toLocate);
                                        postWcsEntity.setTrkType("OT");
                                        postWcsEntity.setTrkPrty(prty);
                                        postWcsEntity.setCreateDate(now);
                                        postWcsEntity.setUpdateDate(now);
                                        postWcsEntity.setCreator(userId);
                                        postWcsEntity.setUpdater(userId);
                                        postWcsService.insert(postWcsEntity);

                                    }
                                }

                                if (!((bindQty.add(obj.getBindQty())).compareTo(obj.getPlanQty()) < 0))
                                    break;//配货数量>=计划数量，跳出循环
                            }
                        }
                    }

                    //查看本次出库的区域
                    int dvcCount = 0;
                    try {
                        dvcCount = baseDao.selectOrderDvcCount(orderId);
                    } catch (Exception ex) {
                        dvcCount = 0;
                    }

                    result.setCode("0");
                    if (dvcCount == 2) {
                        result.setMsg("工單[" + orderId + "]出庫執行成功,有兩個區域的出庫任務");
                        //resultMsg = resultMsg + "工單[" + orderId + "]出庫執行成功,有兩個區域的出庫任務;";
                    } else {
                        result.setMsg("工單[" + orderId + "]出庫執行成功");
                        //resultMsg = resultMsg + "工單[" + orderId + "]出庫執行成功;";
                    }

                } else {

                    result.setCode("0");
                    result.setMsg("工单[" + orderId + "]已經出庫完成");
                    //resultMsg = resultMsg + "工单[" + orderId + "]已經出庫完成;";

                }


                //}

                //}
//                result.setCode("0");
//                result.setMsg(resultMsg);

            } else if (requestType.equals("4")) {
                //紧急出庫detail_id
                List<String> strArray = (List<String>) params.get("detailIds");

                List<Long> detailIds = strArray.stream()
                        .map(Long::parseLong)
                        .collect(Collectors.toList());

                //插入order_reel
                //更新库存状态
                //生成任务和WCS任务
                for (Long detailId : detailIds) {
                    OrderDetailEntity obj = orderDetailDao.selectOne(new QueryWrapper<OrderDetailEntity>()
                            .eq("detail_id", detailId));

                    obj.setIsUg(1);
                    orderDetailDao.updateById(obj);//更新紧急出库
                    // 对obj进行配货
                    BigDecimal bindQty = obj.getBindQty();
                    if ((bindQty.compareTo(obj.getPlanQty()) < 0)) {

                        String spuNo = obj.getSpuNo();
                        //BigDecimal needQty= obj.getPlanQty().subtract(obj.getBindQty());
                        //将queryWrapper单独取出做条件判断
                        QueryWrapper<StockEntity> qwJStock = new QueryWrapper<>();
                        qwJStock.eq("spu_no", spuNo);
                        qwJStock.eq("stock_st", 0);
                        qwJStock.eq("lock_st", 0);
                        qwJStock.eq("position_type", obj.getLocate());
                        qwJStock.eq("stock_type", "1");
                        qwJStock.orderByAsc("stock_qty");
                        qwJStock.orderByAsc("unit_name");

                        List<StockEntity> stocks = stockDao.selectList(qwJStock);

                        for (StockEntity inve : stocks) {
                            //生成出库明细order_reel
                            if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                                    .eq("reel_id", inve.getReelId())
                                    .eq("detail_st", 0))) {
                                //此reelid不存在出库任务
                                OrderReelEntity insertOrderReel = new OrderReelEntity();
                                insertOrderReel.setContNo(inve.getContNo());
                                insertOrderReel.setLocate(inve.getCurPosition());
                                insertOrderReel.setContLocateNo(inve.getContLocateNo());
                                insertOrderReel.setSupplier(inve.getPositionType());
                                insertOrderReel.setDatecode(inve.getUnitName());
//                                insertOrderReel.setStockType(inve.getStockType() + "#1");
                                insertOrderReel.setComments("紧急出庫");

                                insertOrderReel.setReelId(inve.getReelId());
                                insertOrderReel.setPlanQty(inve.getStockQty());
                                insertOrderReel.setZllbh(obj.getZllbh());
                                insertOrderReel.setSpuNo(spuNo);
                                insertOrderReel.setLotNo(inve.getUnitCode());
                                insertOrderReel.setDetailId(obj.getDetailId());
                                insertOrderReel.setCreateDate(now);
                                insertOrderReel.setUpdateDate(now);
                                insertOrderReel.setCreator(userId);
                                insertOrderReel.setUpdater(userId);
                                orderReelDao.insert(insertOrderReel);
                                //更新库存状态
                                StockEntity stockUpdate = new StockEntity();
                                stockUpdate.setStockId(inve.getStockId());
                                stockUpdate.setStockType("1");
                                stockUpdate.setStockSt(1);
                                stockDao.updateById(stockUpdate);

                                //更新出库单配货数量
                                bindQty = bindQty.add(inve.getStockQty());
                                OrderDetailEntity orderDetailUpdate = new OrderDetailEntity();
                                orderDetailUpdate.setDetailId(obj.getDetailId());
                                orderDetailUpdate.setBindQty(bindQty);
                                orderDetailUpdate.setDetailSt(1);
                                orderDetailDao.updateById(orderDetailUpdate);
                                //生成出库任务（有就不生成）（WMS+WCS）
                                if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("task_type", "2")
                                        .lt("task_st", 2))) {
                                    //不存在就下任务
                                    //生成出库任务
                                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                            .eq("locate_no", inve.getCurPosition()));

                                    String locateType = locate.getLocateType();
                                    if (locateType.equals("HW")) {
                                        dvcNo = locate.getDvcNo();

                                        try {
                                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                                    .eq("locate_type", "STS")
                                                    .eq("active", 1)
                                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                                        } catch (Exception ex) {
                                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                                        }
                                        TaskEntity taskEntity = new TaskEntity();

                                        taskEntity.setTaskType("02");
                                        taskEntity.setTaskSubType("021");
                                        taskEntity.setContNo(inve.getContNo());
                                        taskEntity.setComments("料箱紧急出库");
                                        taskEntity.setTaskSt(1);
                                        taskEntity.setFromPosition(inve.getCurPosition());
                                        taskEntity.setCurrentPosition(inve.getCurPosition());
                                        taskEntity.setToPosition(toLocate);
                                        taskEntity.setCreateDate(now);
                                        taskEntity.setUpdateDate(now);
                                        taskEntity.setCreator(userId);
                                        taskEntity.setUpdater(userId);

                                        insert(taskEntity);
                                        //wms_post_wcs下发设备任务
                                        String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                                        PostWcsEntity postWcsEntity = new PostWcsEntity();
                                        postWcsEntity.setContNo(inve.getContNo());
                                        postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                                        postWcsEntity.setContType(contType);
                                        postWcsEntity.setFrmPos(inve.getCurPosition());
                                        postWcsEntity.setCurPos(inve.getCurPosition());
                                        postWcsEntity.setToPos(toLocate);
                                        postWcsEntity.setTrkType("OT");
                                        postWcsEntity.setTrkPrty("3");
                                        postWcsEntity.setCreateDate(now);
                                        postWcsEntity.setUpdateDate(now);
                                        postWcsEntity.setCreator(userId);
                                        postWcsEntity.setUpdater(userId);
                                        postWcsService.insert(postWcsEntity);

                                    }
                                }

                                if (!(bindQty.compareTo(obj.getPlanQty()) < 0))
                                    break;//配货数量>=计划数量，跳出循环

                            }

                        }

                    }
                    //最后给这个单子的出库箱提高优先级
                    try {
                        List<OrderReelEntity> reelList = orderReelDao.selectList(new QueryWrapper<OrderReelEntity>()
                                .eq("detail_id", detailId)
                                .eq("detail_st", 0));
                        for (OrderReelEntity reel : reelList) {
                            try {
                                PostWcsEntity upwcs = postWcsDao.selectOne(new QueryWrapper<PostWcsEntity>()
                                        .eq("cont_no", reel.getContNo())
                                        .eq("trk_st", 1)
                                        .eq("trk_prty", "1"));
                                upwcs.setTrkPrty("3");
                                upwcs.setTrkSt(0);
                                postWcsDao.updateById(upwcs);

                            } catch (Exception ex) {

                            }

                        }
                    } catch (Exception ex) {

                    }

                }
                result.setCode("0");
                result.setMsg("紧急出庫執行成功");

            } else if (requestType.equals("5")) {
                //首套料出庫，每个工单每个物料出一个reelid add 20241207
                Long detailId = Long.parseLong((String) params.get("detailId"));
                String orderId = orderDetailDao.selectById(detailId).getZllbh();

                //配货，
                List<OrderDetailEntity> orderDetails = orderDetailDao.selectList(new QueryWrapper<OrderDetailEntity>()
                        .eq("zllbh", orderId)
                        .apply("plan_qty > bind_qty")
                        .apply("bind_qty = 0"));//需要配0配货数量的

                if (orderDetails.stream().count() > 0) {

                    int succBind = 0;
                    for (OrderDetailEntity obj : orderDetails) {
                        // 对obj进行配货
                        String spuNo = obj.getSpuNo();
                        //查看此工单此物料有没有出库过
                        if (orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                                .eq("zllbh", orderId)
                                .eq("spu_no", spuNo))) {
                            //只要有出库记录就不出库了
                            continue;

                        }

                        //BigDecimal needQty= obj.getPlanQty().subtract(obj.getBindQty());
                        //将queryWrapper单独取出做条件判断
                        QueryWrapper<StockEntity> qwCStock = new QueryWrapper<>();
                        qwCStock.eq("spu_no", spuNo);
                        qwCStock.eq("stock_st", 0);
                        qwCStock.eq("lock_st", 0);
                        qwCStock.eq("position_type", obj.getLocate());
                        qwCStock.eq("stock_type", "1");
                        qwCStock.orderByAsc("stock_qty");
                        qwCStock.orderByAsc("unit_name");
                        qwCStock.last("limit 1");//只取一盘库存

                        try {
                            StockEntity inve = stockDao.selectOne(qwCStock);

                            BigDecimal bindQty = obj.getBindQty();

                            //生成出库明细order_reel
                            if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                                    .eq("reel_id", inve.getReelId())
                                    .eq("detail_st", 0))) {
                                succBind++;
                                //此reelid不存在出库任务
                                OrderReelEntity insertOrderReel = new OrderReelEntity();
                                insertOrderReel.setContNo(inve.getContNo());
                                insertOrderReel.setLocate(inve.getCurPosition());
                                insertOrderReel.setContLocateNo(inve.getContLocateNo());
                                insertOrderReel.setSupplier(inve.getPositionType());
                                insertOrderReel.setDatecode(inve.getUnitName());
//                                insertOrderReel.setStockType(inve.getStockType() + "#1");
                                insertOrderReel.setComments("工單首套料出庫");

                                insertOrderReel.setReelId(inve.getReelId());
                                insertOrderReel.setPlanQty(inve.getStockQty());
                                insertOrderReel.setZllbh(orderId);
                                insertOrderReel.setSpuNo(spuNo);
                                insertOrderReel.setLotNo(inve.getUnitCode());
                                insertOrderReel.setDetailId(obj.getDetailId());
                                insertOrderReel.setCreateDate(now);
                                insertOrderReel.setUpdateDate(now);
                                insertOrderReel.setCreator(userId);
                                insertOrderReel.setUpdater(userId);
                                orderReelDao.insert(insertOrderReel);
                                //更新库存状态
                                StockEntity stockUpdate = new StockEntity();
                                stockUpdate.setStockId(inve.getStockId());
                                stockUpdate.setStockSt(1);
                                stockDao.updateById(stockUpdate);

                                //更新出库单配货数量
                                bindQty = bindQty.add(inve.getStockQty());
                                OrderDetailEntity orderDetailUpdate = new OrderDetailEntity();
                                orderDetailUpdate.setDetailId(obj.getDetailId());
                                orderDetailUpdate.setBindQty(bindQty);
                                orderDetailUpdate.setDetailSt(1);
                                orderDetailDao.updateById(orderDetailUpdate);
                                //生成出库任务（有就不生成）（WMS+WCS）
                                if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("task_type", "2")
                                        .lt("task_st", 2))) {
                                    //不存在就下任务
                                    //生成出库任务
                                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                            .eq("locate_no", inve.getCurPosition()));

                                    String locateType = locate.getLocateType();
                                    if (locateType.equals("HW")) {
                                        dvcNo = locate.getDvcNo();

                                        try {
                                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                                    .eq("locate_type", "STS")
                                                    .eq("active", 1)
                                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                                        } catch (Exception ex) {
                                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                                        }
                                        TaskEntity taskEntity = new TaskEntity();

                                        taskEntity.setTaskType("02");
                                        taskEntity.setTaskSubType("021");
                                        taskEntity.setContNo(inve.getContNo());
                                        taskEntity.setComments("料箱工单首套料出库");
                                        taskEntity.setTaskSt(1);
                                        taskEntity.setFromPosition(inve.getCurPosition());
                                        taskEntity.setCurrentPosition(inve.getCurPosition());
                                        taskEntity.setToPosition(toLocate);
                                        taskEntity.setCreateDate(now);
                                        taskEntity.setUpdateDate(now);
                                        taskEntity.setCreator(userId);
                                        taskEntity.setUpdater(userId);

                                        insert(taskEntity);
                                        //wms_post_wcs下发设备任务
                                        String prty = "3";
//                                        if (obj.getIsUg() == 1)
//                                            prty = "3";
                                        String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                                        PostWcsEntity postWcsEntity = new PostWcsEntity();
                                        postWcsEntity.setContNo(inve.getContNo());
                                        postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                                        postWcsEntity.setContType(contType);
                                        postWcsEntity.setFrmPos(inve.getCurPosition());
                                        postWcsEntity.setCurPos(inve.getCurPosition());
                                        postWcsEntity.setToPos(toLocate);
                                        postWcsEntity.setTrkType("OT");
                                        postWcsEntity.setTrkPrty(prty);
                                        postWcsEntity.setCreateDate(now);
                                        postWcsEntity.setUpdateDate(now);
                                        postWcsEntity.setCreator(userId);
                                        postWcsEntity.setUpdater(userId);
                                        postWcsService.insert(postWcsEntity);
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            //説明沒有庫存，不報錯
                            continue;
                        }

                    }

                    if (succBind > 0) {
                        //查看本次出库的区域
                        int dvcCount = 0;
                        try {
                            dvcCount = baseDao.selectOrderDvcCount(orderId);
                        } catch (Exception ex) {
                            dvcCount = 0;
                        }

                        result.setCode("0");
                        if (dvcCount == 2) {
                            result.setMsg("工單[" + orderId + "]首套料出庫執行成功,有兩個區域的出庫任務");
                        } else {
                            result.setMsg("工單[" + orderId + "]首套料出庫執行成功");
                        }


                    } else {
                        result.setCode("-1");
                        result.setMsg("工單[" + orderId + "]首套料出庫執行失敗：庫存不足");
                    }


                } else {

                    result.setCode("-1");
                    result.setMsg("工单[" + orderId + "]已經執行首套料出庫");

                }

            } else if (requestType.equals("6")) {
                //reelid批量出库
                //更新 2025-1-2，波次出库，批量

                Long detailId = Long.parseLong((String) params.get("detailId"));

                String waveNo = orderDetailDao.selectById(detailId).getWaveNo();


                //配货
                List<OrderDetailEntity> orderDetails = orderDetailDao.selectList(new QueryWrapper<OrderDetailEntity>()
                        .eq("wave_no", waveNo)
                        .apply("plan_qty = 0"));

                if (orderDetails.stream().count() > 0) {
                    for (OrderDetailEntity obj : orderDetails) {
                        // 对obj进行配货
                        String reelId = obj.getReelId();
                        //BigDecimal needQty= obj.getPlanQty().subtract(obj.getBindQty());
                        //将queryWrapper单独取出做条件判断
                        QueryWrapper<StockEntity> qwCStock = new QueryWrapper<>();
                        qwCStock.eq("reel_id", reelId);
                        qwCStock.eq("stock_st", 0);
                        qwCStock.eq("lock_st", 0);

                        List<StockEntity> stocks = stockDao.selectList(qwCStock);

                        BigDecimal bindQty = obj.getBindQty();
                        for (StockEntity inve : stocks) {
                            //生成出库明细order_reel
                            if (!orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                                    .eq("reel_id", inve.getReelId())
                                    .eq("detail_st", 0))) {
                                //此reelid不存在出库任务
                                OrderReelEntity insertOrderReel = new OrderReelEntity();
                                insertOrderReel.setContNo(inve.getContNo());
                                insertOrderReel.setLocate(inve.getCurPosition());
                                insertOrderReel.setContLocateNo(inve.getContLocateNo());
                                insertOrderReel.setSupplier(inve.getPositionType());
                                insertOrderReel.setDatecode(inve.getUnitName());
//                                insertOrderReel.setStockType(inve.getStockType() + "#1");
                                insertOrderReel.setComments("reelid批量出庫");

                                insertOrderReel.setReelId(inve.getReelId());
                                insertOrderReel.setPlanQty(inve.getStockQty());
                                //insertOrderReel.setZllbh(orderId);
                                insertOrderReel.setSpuNo(inve.getSpuNo());
                                insertOrderReel.setLotNo(inve.getUnitCode());
                                insertOrderReel.setDetailId(obj.getDetailId());
                                insertOrderReel.setCreateDate(now);
                                insertOrderReel.setUpdateDate(now);
                                insertOrderReel.setCreator(userId);
                                insertOrderReel.setUpdater(userId);
                                orderReelDao.insert(insertOrderReel);
                                //更新库存状态
                                StockEntity stockUpdate = new StockEntity();
                                stockUpdate.setStockId(inve.getStockId());
                                stockUpdate.setStockType("1");
                                stockUpdate.setStockSt(1);
                                stockDao.updateById(stockUpdate);

                                //更新出库单配货数量
                                bindQty = bindQty.add(inve.getStockQty());

                                OrderDetailEntity orderDetailUpdate = new OrderDetailEntity();
                                orderDetailUpdate.setPlanQty(inve.getStockQty());
                                orderDetailUpdate.setDetailId(obj.getDetailId());
                                orderDetailUpdate.setBindQty(bindQty);
                                orderDetailUpdate.setDetailSt(1);
                                orderDetailDao.updateById(orderDetailUpdate);
                                //生成出库任务（有就不生成）（WMS+WCS）
                                if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                                        .eq("cont_no", inve.getContNo())
                                        .eq("task_type", "2")
                                        .lt("task_st", 2))) {
                                    //不存在就下任务
                                    //生成出库任务
                                    LocateEntity locate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                            .eq("locate_no", inve.getCurPosition()));

                                    String locateType = locate.getLocateType();
                                    if (locateType.equals("HW")) {
                                        dvcNo = locate.getDvcNo();

                                        try {
                                            toLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                                                    .eq("locate_type", "STS")
                                                    .eq("active", 1)
                                                    .eq("dvc_no", dvcNo)).getLocateNo();//操作货位;

                                        } catch (Exception ex) {
                                            throw new Exception("找不到" + dvcNo + "區上料口貨位");
                                        }
                                        TaskEntity taskEntity = new TaskEntity();

                                        taskEntity.setTaskType("02");
                                        taskEntity.setTaskSubType("021");
                                        taskEntity.setContNo(inve.getContNo());
                                        taskEntity.setComments("料箱工单出库");
                                        taskEntity.setTaskSt(1);
                                        taskEntity.setFromPosition(inve.getCurPosition());
                                        taskEntity.setCurrentPosition(inve.getCurPosition());
                                        taskEntity.setToPosition(toLocate);
                                        taskEntity.setCreateDate(now);
                                        taskEntity.setUpdateDate(now);
                                        taskEntity.setCreator(userId);
                                        taskEntity.setUpdater(userId);

                                        insert(taskEntity);
                                        //wms_post_wcs下发设备任务
                                        String prty = "1";
                                        if (obj.getIsUg() == 1)
                                            prty = "3";
                                        String contType = inve.getContNo().charAt(0) == 'B' ? "2" : "1";
                                        PostWcsEntity postWcsEntity = new PostWcsEntity();
                                        postWcsEntity.setContNo(inve.getContNo());
                                        postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                                        postWcsEntity.setContType(contType);
                                        postWcsEntity.setFrmPos(inve.getCurPosition());
                                        postWcsEntity.setCurPos(inve.getCurPosition());
                                        postWcsEntity.setToPos(toLocate);
                                        postWcsEntity.setTrkType("OT");
                                        postWcsEntity.setTrkPrty(prty);
                                        postWcsEntity.setCreateDate(now);
                                        postWcsEntity.setUpdateDate(now);
                                        postWcsEntity.setCreator(userId);
                                        postWcsEntity.setUpdater(userId);
                                        postWcsService.insert(postWcsEntity);

                                    }
                                }

                                if (!(bindQty.compareTo(obj.getPlanQty()) < 0))
                                    break;//配货数量>=计划数量，跳出循环
                            }

                        }
                    }
                }
                result.setCode("0");
                result.setMsg("reelid批量出庫成功");

            } else {
                //返回失败
                result.setCode("-1");
                result.setMsg("出庫【" + requestType + "】類型錯誤");
            }
        } catch (Exception ex) {
            //返回失败
            result.setCode("-1");
            result.setMsg(ex.toString());
        }
//        sysSysLogWorkService.workLogging("出库请求",
//                "",
//                result.getCode(),
//                result.getMsg().substring(0,499),
//                "requestContOut",
//                userName,
//                0);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProcResult requestContIn(Map<String, Object> params) {
        //由于入库登记直接分配货位，所以所有入库登记都用这个方法
        ProcResult result = new ProcResult();
        String userName = SecurityUser.getUser().getRealName();

        try {
            String requestType = (String) params.get("requestType");//0-空托盘登记 1-入库登记 2-盘点回库
            String stn = (String) params.get("stn");
            String dvcNo = stn.equals("A区") ? "A" : "B";
            String fromLocate = "";

            try {
                fromLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                        .eq("locate_type", "STX")
                        .eq("active", 1)
                        .eq("dvc_no", dvcNo)).getLocateNo();//操作货位

            } catch (Exception ex) {
                throw new Exception("找不到" + stn + "下料口貨位");
            }

            Long userId = SecurityUser.getUser().getId();
            Date now = new Date();
            if (requestType.equals("0")) {
                //空箱入库
                //输入托盘号+托盘类型
                //生成容器信息和容器明细货格
                //分配货位，生成入库任务
                String contNo = (String) params.get("contNo");//箱码
                //String contType = (String) params.get("contType");//容器规格
                String countType = (String) params.get("countType");

                String contVolume = (String) params.get("contVolume");//體積
                //容器的货格号，只针对B，10格  2   16格 3
//                if(contNo.charAt(0)=='B' && countType.equals("1"))
//                {
//                    throw new Exception("未正确选择大料箱【"+contNo+"】的类型");
//                }
                String[] parts = contVolume.split("\\*"); // 使用split方法，并使用转义的*作为分隔符
                String lastPart = parts[parts.length - 1]; // 获取最后一个部分

                //String contType = contNo.charAt(0)=='B'?countType:"1";//容器规格
                String contType = countType;
                String toLocate = "";//入库目标货位


                //查看此容器是否存在，存在就报错
                QueryWrapper<ContainerEntity> contWrapper = new QueryWrapper<ContainerEntity>()
                        .eq("cont_no", contNo);
                if (containerDao.exists(contWrapper)) {
                    throw new Exception("此箱碼已登記，不允許重複登記");
                }
                if (stockDao.exists(new QueryWrapper<StockEntity>()
                        .eq("cont_no", contNo))) {
                    throw new Exception("此箱碼已有庫存，不允許重複登記");
                }
                try {
                    ContainerEntity contInsert = new ContainerEntity();
                    contInsert.setContNo(contNo);
                    contInsert.setContType(contType);
                    contInsert.setContDescription(contVolume);
                    contInsert.setContHeight(lastPart);
                    contInsert.setCreateDate(now);
                    contInsert.setUpdateDate(now);
                    contInsert.setCreator(userId);
                    contInsert.setUpdater(userId);
                    if (containerService.insert(contInsert)) {
                        //查看此容器货格是否存在，存在就报错
                        QueryWrapper<ContainerDetailEntity> contDtWrapper = new QueryWrapper<ContainerDetailEntity>()
                                .eq("cont_no", contNo);
                        if (containerDetailDao.exists(contDtWrapper)) {
                            //没有主表信息有明细信息？这个情况不正常

                            //result.setMsg("此箱码已有货格信息，不能重复登记");
                            throw new Exception("此箱碼已有貨格信息，不允許重複登記");
                        }

                        //批量插入  16或10个货格信息//都是16格
                        List<ContainerDetailEntity> contDtList = new ArrayList<>();

                        int detailCount = 1;

                        if (contType.equals("2"))
                            detailCount = 10;
                        if (contType.equals("3"))
                            detailCount = 16;


                        for (int i = 1; i <= detailCount; i++) {
                            ContainerDetailEntity contDtInsert = new ContainerDetailEntity();
                            contDtInsert.setContNo(contNo);
                            contDtInsert.setContLocateNo(contNo + "-" + i);
                            contDtInsert.setCreateDate(now);
                            contDtInsert.setUpdateDate(now);
                            contDtInsert.setCreator(userId);
                            contDtInsert.setUpdater(userId);
                            contDtList.add(contDtInsert);
                        }
                        containerDetailService.insertBatch(contDtList);
                    }
                    //不用生產任務數據，放行生成
                    result.setCode("0");
                    result.setMsg("箱号【" + contNo + "】登记成功");
                } catch (Exception ex) {
                    throw new Exception(ex.toString());
                }

            } else if (requestType.equals("1")) {
                //reelid 登记入库
                //输入参数 reelid，料箱号，物料号，批号，数量，datecode，货格号
                //生成库存
                //生成入库单据
                //生成搬运任务（分配货位+生成WCS任务）
                //回写ERPreel和LOG
                String contNo = (String) params.get("contNo");//箱码
                String contLocateNo = (String) params.get("contLocateNo");//货格
                String inType = (String) params.get("inType");//厂商交货入库/零星入库
                String reelId = (String) params.get("reelId");//reelId
                String itemId = (String) params.get("itemId");//物料编号
                String itemType = (String) params.get("itemType");//物料类型
                String stockType = (String) params.get("stockType");//库存类型（小庫-綫邊庫&大庫-原料庫）add 2024年11月20日
                //String contType = contNo.charAt(0)=='B'?"2":"1";//托盘类型，用来校验物料类型
                String lot = (String) params.get("lot");//批号
                Long qnty = Long.parseLong((String) params.get("qnty"));//数量
                String datecode = (String) params.get("dcode");//datecode
                String supplier = (String) params.get("supplier");//供应商
                String itemLength = (String) params.get("itemLength");//長
                String itemWidth = (String) params.get("itemWidth");//寬
                String itemHeight = (String) params.get("itemHeight");//高

                String contType = containerDao.selectOne(new QueryWrapper<ContainerEntity>()
                        .eq("cont_no", contNo)).getContType();

//                String fromLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
//                        .eq("locate_type","ST")).getLocateNo();//操作货位
                String toLocate = "";//入库目标货位
                String userNo = SecurityUser.getUser().getUsername();

                //托盘类型，用来校验物料类型???
                if (itemLength == null || itemLength.isEmpty()) {
                    throw new Exception("reelid[" + reelId + "]需要輸入長度信息");
                }
                if (itemWidth == null || itemWidth.isEmpty()) {
                    throw new Exception("reelid[" + reelId + "]需要輸入寬度信息");
                }
                if (itemHeight == null || itemHeight.isEmpty()) {
                    throw new Exception("reelid[" + reelId + "]需要輸入高度信息");
                }

                if (supplier == null || supplier.isEmpty()) {

                    throw new Exception("reelid[" + reelId + "]無庫別資料，請建立正確庫別資料");
                }

                if (contLocateNo == null || contLocateNo.isEmpty()) {

                    throw new Exception("reelid[" + reelId + "]貨格號爲空，請用料箱號確認");
                }
                if (!containerDetailDao.exists(new QueryWrapper<ContainerDetailEntity>()
                        .eq("cont_locate_no", contLocateNo))) {
                    throw new Exception("貨格號[" + contLocateNo + "]错误");
                }

                if (qnty == null || qnty == 0) {

                    throw new Exception("reelid[" + reelId + "]入庫數量需要大於0");
                }

                if (datecode == null || datecode.isEmpty()) {

                    throw new Exception("reelid[" + reelId + "]datecode無");
                }
                //校验货格有没有装库存
                if (stockDao.exists(new QueryWrapper<StockEntity>()
                        .eq("reel_id", reelId))) {
                    throw new Exception("reelid[" + reelId + "]已登記入庫");
                }

                //校验REELID是否已入库
                if ((stockDao.exists(new QueryWrapper<StockEntity>()
                        .eq("cont_locate_no", contLocateNo))) &&
                        (contType.equals("2") || contType.equals("3"))) {
                    throw new Exception("貨格[" + contLocateNo + "]已存在庫存");
                }

                //加超高限制
                String contHeight = containerDao.selectOne(new QueryWrapper<ContainerEntity>()
                        .eq("cont_no", contNo)).getContHeight();
                double contHeight1 = Double.parseDouble(contHeight);
                double itemHeight1 = Double.parseDouble(itemHeight);

                if (itemHeight1 > contHeight1) {
                    throw new Exception("reelid[" + reelId + "]物料高度[" + itemHeight + "]超過料箱高度[" + contHeight + "]");
                }

                //安全空间限制

                BigDecimal useRate = baseDao.getStockSafe();
                String safeRateStr = sysParamsDao.getValueByCode("PERCENTAGE");
                BigDecimal safeRate = new BigDecimal(safeRateStr);
                if (useRate.compareTo(safeRate) > 0) {
                    throw new Exception("空間利用率[" + useRate + "]超過了設定的安全值[" + safeRateStr + "]");
                }
                StockEntity stockInsert = new StockEntity();
                stockInsert.setContNo(contNo);
                stockInsert.setCurPosition(fromLocate);
                stockInsert.setSpuNo(itemId);
                stockInsert.setUnitCode(lot);
                stockInsert.setReelId(reelId);
                stockInsert.setUnitName(datecode);
                stockInsert.setLength(itemLength);
                stockInsert.setWidth(itemWidth);
                stockInsert.setHeight(itemHeight);
                stockInsert.setContLocateNo(contLocateNo);
                stockInsert.setStockQty(new BigDecimal(qnty));
                stockInsert.setPositionType(supplier);//ADD 9/24库别
                stockInsert.setCreateDate(now);
                stockInsert.setUpdateDate(now);
                stockInsert.setCreator(userId);
                stockInsert.setUpdater(userId);
                stockInsert.setStockType(stockType);//add 2024年11月20日
                if (stockDao.insert(stockInsert) > 0) {
                    //生成入库单
                    PurchaseDetailEntity purchaseInsert = new PurchaseDetailEntity();

                    purchaseInsert.setSpuNo(itemId);
                    purchaseInsert.setUnitCode(lot);
                    purchaseInsert.setUnitName(datecode);
                    purchaseInsert.setLineNo(reelId);
                    purchaseInsert.setDeliverNo(supplier);
                    purchaseInsert.setPlanQty(new BigDecimal(qnty));
                    purchaseInsert.setContNo(contNo);
                    purchaseInsert.setContLocateNo(contLocateNo);
                    purchaseInsert.setOrderRowNo("0");
                    purchaseInsert.setLength(itemLength);
                    purchaseInsert.setWidth(itemWidth);
                    purchaseInsert.setHeight(itemHeight);
                    purchaseInsert.setComments(inType);
                    purchaseInsert.setCreateDate(now);
                    purchaseInsert.setUpdateDate(now);
                    purchaseInsert.setCreator(userId);
                    purchaseInsert.setUpdater(userId);
                    purchaseInsert.setStockType(stockType);//add 2025,1,5
                    purchaseDetailDao.insert(purchaseInsert);
                }

                //查看有沒有物料信息，沒有就新建一條，有就更新長寬高
                if (spuDao.exists(new QueryWrapper<SpuEntity>()
                        .eq("spu_no", itemId))) {
                    SpuEntity updateSpu = spuDao.selectOne(new QueryWrapper<SpuEntity>()
                            .eq("spu_no", itemId));
                    updateSpu.setSpuType(itemLength);//長
                    updateSpu.setSpuSpec(itemWidth);//寬
                    updateSpu.setSpuUnit(itemHeight);//高
                    updateSpu.setUpdater(userId);
                    updateSpu.setUpdateDate(now);
                    spuDao.updateById(updateSpu);
                } else {
                    SpuEntity insertSpu = new SpuEntity();
                    insertSpu.setSpuNo(itemId);
                    insertSpu.setSpuType(itemLength);//長
                    insertSpu.setSpuSpec(itemWidth);//寬
                    insertSpu.setSpuUnit(itemHeight);//高
                    insertSpu.setCreator(userId);
                    insertSpu.setCreateDate(now);
                    insertSpu.setUpdater(userId);
                    insertSpu.setUpdateDate(now);
                    spuDao.insert(insertSpu);
                }


                //最后写入ERP日志
//                try {
//                    ErpReelEntity updateReel = new ErpReelEntity();
//                    updateReel.setRstation(contLocateNo);
//                    updateReel.setRid(reelId);
//                    erpReelDao.updateReel(updateReel);
//
//                    ErpLogEntity logInsert = new ErpLogEntity();
//                    logInsert.setRid(reelId);
//                    logInsert.setPn(itemId);
//                    logInsert.setQty(qnty);
//                    logInsert.setEventid("LGRSTACG");
//                    logInsert.setStation(contLocateNo);
//                    logInsert.setCompany("PEGATRON");
//                    logInsert.setTimestamp(now);
//                    logInsert.setRemarks("IN," + contLocateNo + "," + userName);
//                    logInsert.setUid(userNo);
//                    erplogDao.insertLog(logInsert);
//                }
//                catch (Exception ex){
//                    //只记录日志，不管结果
//                    System.out.println(ex);
//
//                }

                PostSapEntity postSapEntity = new PostSapEntity();
                postSapEntity.setLgnum(reelId);
                postSapEntity.setUname(itemId);
                postSapEntity.setSrmdn(contLocateNo);
                postSapEntity.setMenge(new BigDecimal(qnty));
                postSapEntity.setCreator(userId);
                postSapEntity.setComments("IN," + contLocateNo + "," + userName);
                postSapEntity.setMsgType("IN");
                postSapEntity.setCreateDate(now);
                postSapDao.insert(postSapEntity);

                result.setCode("0");
                result.setMsg("reelid[" + reelId + "]登記入庫成功");


            }

        } catch (Exception ex) {
            result.setCode("-1");
            result.setMsg(ex.toString());
        }
//        sysSysLogWorkService.workLogging("入库登记",
//                "",
//                result.getCode(),
//                result.getMsg().substring(0,200),
//                "requestContIn",
//                userName,
//                0);
        return result;
    }

    @Override
    public PageData<ErpReelDTO> reelAsk(String reelId) {
        QueryWrapper<ErpReelEntity> erpReelWrapper = new QueryWrapper<ErpReelEntity>()
                .eq("RID", reelId);

        final IPage<ErpReelEntity> page = erpReelDao.selectPage(new Page<>(1, 10),
                erpReelWrapper
        );
        return getPageData(page, ErpReelDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProcResult contBack(Map<String, Object> params) {
        ProcResult result = new ProcResult();

        try {
            String contNo = (String) params.get("contNo");//0-空托盘登记 1-入库登记 2-盘点回库
            String contType = contNo.charAt(0) == 'B' ? "2" : "1";//容器规格
            String stn = (String) params.get("stn");
            String dvcNo = stn.equals("A区") ? "A" : "B";
            String fromLocate = "";
            String toLocate = "";//入库目标货位

            try {
                fromLocate = locateDao.selectOne(new QueryWrapper<LocateEntity>()
                        .eq("locate_type", "STX")
                        .eq("active", 1)
                        .eq("dvc_no", dvcNo)).getLocateNo();//操作货位

            } catch (Exception ex) {
                throw new Exception("找不到" + stn + "下料口貨位");
            }

            Long userId = SecurityUser.getUser().getId();
            Date now = new Date();

            if (!containerDao.exists(new QueryWrapper<ContainerEntity>()
                    .eq("cont_no", contNo))) {
                throw new Exception("箱碼[" + contNo + "]未登記");
            }

            if (locateDao.exists(new QueryWrapper<LocateEntity>()
                    .eq("locate_type", "HW")
                    .eq("cont_no", contNo))) {
                throw new Exception("箱碼[" + contNo + "]在庫位上");
            }

            //查看有没有出库任务
            if (orderReelDao.exists(new QueryWrapper<OrderReelEntity>()
                    .eq("cont_no", contNo)
                    .eq("detail_st", 0))) {

                throw new Exception("箱碼[" + contNo + "]有庫存需要揀貨出庫");
            }

            if (!baseDao.exists(new QueryWrapper<TaskEntity>()
                    .eq("cont_no", contNo)
                    .lt("task_st", 2))) {
                //查看料箱高度
                String contHeight = containerDao.selectOne(new QueryWrapper<ContainerEntity>()
                        .eq("cont_no", contNo)).getContHeight();
                //不存在任务就生成任务
                //创建入库任务
                //插入成功，分配货位，生成任务
                QueryWrapper<LocateEntity> locateWrapper = null;
                //if(contType.equals("2"))
                if (contHeight.equals("38"))//38cm高入高曾
                {
                    locateWrapper = new QueryWrapper<LocateEntity>()
                            .eq("locate_type", "HW")
                            .eq("active", 1)
                            .eq("dvc_no", dvcNo)
                            .eq("high_level", "1")
                            .eq("locate_st", 0)
                            .orderByAsc("row_num") //優先排  近-》遠
                            .orderByAsc("level_num")//優先層  低-》高
                            .orderByAsc("col_num");

                } else {
                    locateWrapper = new QueryWrapper<LocateEntity>()
                            .eq("locate_type", "HW")
                            .eq("active", 1)
                            .eq("dvc_no", dvcNo)
                            .eq("locate_st", 0)
                            .orderByAsc("high_level")
                            .orderByAsc("row_num") //優先排  近-》遠
                            .orderByAsc("level_num")//優先層  低-》高
                            .orderByAsc("col_num");
                }

                LocateEntity toLocateEntity;
                try {
                    toLocateEntity = locateDao.selectList(locateWrapper).get(0);
                } catch (Exception ex) {
                    throw new Exception("庫裏已滿，無空庫位");
                }

                toLocate = toLocateEntity.getLocateNo();
                //货位状态  更新为已分配
                toLocateEntity.setLocateSt(1);
                locateDao.updateById(toLocateEntity);

                //下发出库任务 wms_task + wms_post_wcs
                TaskEntity taskEntity = new TaskEntity();

                taskEntity.setTaskType("01");
                taskEntity.setTaskSubType("011");
                taskEntity.setContNo(contNo);
                taskEntity.setComments("料箱放行");
                taskEntity.setTaskSt(1);
                taskEntity.setFromPosition(fromLocate);
                taskEntity.setCurrentPosition(fromLocate);
                taskEntity.setToPosition(toLocate);
                taskEntity.setCreateDate(now);
                taskEntity.setUpdateDate(now);
                taskEntity.setCreator(userId);
                taskEntity.setUpdater(userId);
                insert(taskEntity);
            } else {
                TaskEntity taskCont = baseDao.selectOne(new QueryWrapper<TaskEntity>()
                        .eq("cont_no", contNo)
                        .lt("task_st", 2));
                if (taskCont.getTaskType().equals("01")) {
                    throw new Exception("箱號【" + contNo + "】已有放行任務");
                }

                if (taskCont.getTaskType().equals("02")) {
                    throw new Exception("箱號【" + contNo + "】出庫任務未結束");
                }

            }

            if (!postWcsDao.exists(new QueryWrapper<PostWcsEntity>()
                    .eq("cont_no", contNo)
                    .eq("trk_type", "IN"))) {

                PostWcsEntity postWcsEntity = new PostWcsEntity();
                postWcsEntity.setContNo(contNo);
                postWcsEntity.setRequestPk(UUID.randomUUID().toString().replace("-", ""));
                postWcsEntity.setContType(contType);
                postWcsEntity.setFrmPos(fromLocate);
                postWcsEntity.setCurPos(fromLocate);
                postWcsEntity.setToPos(toLocate);
                postWcsEntity.setTrkType("IN");
                postWcsEntity.setTrkPrty("1");
                postWcsEntity.setCreateDate(now);
                postWcsEntity.setUpdateDate(now);
                postWcsEntity.setCreator(userId);
                postWcsEntity.setUpdater(userId);
                postWcsService.insert(postWcsEntity);

            }
            result.setCode("0");
            result.setMsg("箱號[" + contNo + "]放行成功");

        } catch (Exception ex) {
            result.setCode("-1");
            result.setMsg(ex.toString());
        }
        return result;
    }

    @Override
    public int selectEmptyCount(Map<String, Object> params) {
        try {
            String contType = (String) params.get("contType");
            String stn = (String) params.get("stn");
            String dvcNo = stn.equals("A区") ? "A" : "B";
            String contVolume = (String) params.get("contVolume");
            return baseDao.selectEmptyCount(contType, dvcNo, contVolume);

        } catch (Exception ex) {
            return 0;
        }

    }

    @Override
    public String getSafeRate() {
        String rate = "0%";
        try {
            rate = baseDao.getStockSafe().toString() + "%";
        } catch (Exception ex) {
            rate = "0%";
        }
        return rate;
    }

}